<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="10"><div class="grid-content bg-purple">
        <div class="developer left">
          <div id="box">
            <ul>
              <li v-for="(v, index) in districtList" :key="index">
                <div class="product-content1">
                  <image-preview :src="v.image" alt="Dynamic Image" class="fixed-image-size"/>
                  <div class="info">
                    <h2>{{ v.communityName }}</h2>
                    <h4>小区地址：暂无地址</h4>
                    <h4>辖区：{{ v.name }}</h4>
                  </div>
                  <div class="additional-info1">
                    <p @click="handlePopulationClick(v.id)">实有人口：{{ v.populationNum }}</p>
                    <p @click="handleEstateClick(v.id)">实有房屋：{{ v.realEstateNum }}</p>
                    <p @click="handleUnitClick(v.id)">实有单位：{{ v.unitNum }}</p>
                    <p @click="handleVehiclesClick(v.id)">实有车辆：{{ v.vehicleNum }}</p>
                    <p @click="handleCacheClick(v.id)">实有力量：{{ v.buildingCount }}</p>
                    <p @click="handleFacilitiesClick(v.id)">实有设备：{{ v.securityFacilitiesNum }}</p>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div></el-col>
      <el-col :span="10"><div class="grid-content bg-purple">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="建造日期" prop="max">
            <el-date-picker clearable
                            v-model="queryParams.max"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="起始日期">
            </el-date-picker>
          </el-form-item>至
          <el-form-item prop="min">
            <el-date-picker clearable
                            v-model="queryParams.min"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="房主" prop="populationId">
            <el-select v-model="queryParams.populationId" :clearable="true" placeholder="请选择房主">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼栋" prop="ridgepole">
            <el-input
              v-model="queryParams.ridgepole"
              placeholder="请输入楼栋"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="单元" prop="element">
            <el-input
              v-model="queryParams.element"
              placeholder="请输入单元"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="楼层" prop="tier">
            <el-input
              v-model="queryParams.tier"
              placeholder="请输入楼层"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="房间号" prop="households">
            <el-input
              v-model="queryParams.households"
              placeholder="请输入房间号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <br>
          <el-form-item label="添加时间" prop="max1">
            <el-date-picker clearable
                            v-model="queryParams.max1"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="开始时间">
            </el-date-picker>
          </el-form-item>至
          <el-form-item prop="min1">
            <el-date-picker clearable
                            v-model="queryParams.min1"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="primary" size="mini" @click="add">添加楼栋</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['community:estate:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"

              @click="handleUpdate"
              v-hasPermi="['community:estate:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"

              @click="handleDelete"
              v-hasPermi="['community:estate:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['community:estate:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--小区实有房屋-->
        <div id="box">
          <ul class="unit-list">
            <li v-for="(v, index) in estateList" :key="index" class="unit-item">
              <div class="product-unit">
                <input type="checkbox" v-model="selectedItems" :value="v.id" class="checkbox-item" @change="handleSelectionChange(v.id)" />
                <div class="image-container">
                <image-preview :src="v.picture" alt="Dynamic Image" class="fixed-image-size1"/>
                </div>
                <br>
                <div class="info">
                  <h4>房屋类型：{{v.estateType}}</h4>
                  <h4>建造日期：{{v.constructionDate}}</h4>
                  <h4>所属小区：{{v.communityName}}</h4>
                  <h4>楼栋：{{ v.ridgepole }}</h4>
                  <h4>单元：{{ v.element }}</h4>
                  <h4>楼层：{{ v.tier }}</h4>
                  <h4>房间号：{{ v.households }}</h4>
                  <h4>房屋人数：{{ v.ridgepole }}</h4>
                  <h4>添加日期：{{ v.createDate }}</h4>
                  <el-button type="primary" plain size="mini"   @click="redirectToestatePage(v)">一屋一档</el-button>
                </div>
              </div>
            </li>
          </ul>
        </div>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div></el-col>
    </el-row>

    <!--添加楼栋对话框-->
    <el-dialog title="新增楼栋" :visible.sync="dialogFormVisible" width="80%">
      <!-- 自定义标题模板 -->
      <span slot="title" style="display: inline-block; background-color: #1890ff; color: #fff; padding: 10px; border-radius: 4px; width: 100%; text-align: left; margin-left: -20px;">
      新增楼栋
      </span>
      <el-form :model="estateForm">
        <el-row>
          <el-col :span="8">
            <el-form-item :label-width="formLabelWidth">
              <template #label>
                <span style="color: red;">*</span>
                楼栋编号:
              </template>
              <el-input-number v-model="estateForm.buildingId" controls-position="right" :min="0" placeholder="请输入楼栋号" autocomplete="off" style="width: 200px"></el-input-number>
              <el-button type="primary">栋</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地图定位:" :label-width="formLabelWidth">
              <el-input v-model="estateForm.communityName" placeholder="点击右侧图标选取地图定位" autocomplete="off" style="width: 200px"></el-input>
              <el-button type="primary" icon="el-icon-location-outline" @click="showMap"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <template>
          <div class="form-container" v-for="(item, index) in estateForm.elementList">
            <el-form-item :label-width="formLabelWidth" class="form-item">
              <template #label>
                <span style="color: red;">*</span>
                单元:
              </template>
              <el-input-number v-model="estateForm.elementList[index].elementId" controls-position="right" :min="0" placeholder="请输入单元号" autocomplete="off" style="width: 100px"></el-input-number>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" class="form-item">
              <template #label>
                <span style="color: red;">*</span>
                起始楼层:
              </template>
              <el-input-number v-model="estateForm.elementList[index].startFloor" controls-position="right" :min="0" placeholder="请输入" autocomplete="off" style="width: 130px"></el-input-number>
              <el-button type="primary" style="margin-left: 3px;">层</el-button>
            </el-form-item>

            <el-form-item :label-width="formLabelWidth" class="form-item">
              <template #label>
                <span style="color: red;">*</span>
                结束楼层:
              </template>
              <el-input-number v-model="estateForm.elementList[index].endFloor" controls-position="right" :min="0" placeholder="请输入" autocomplete="off" style="width: 130px"></el-input-number>
              <el-button type="primary" style="margin-left: 3px;">层</el-button>
            </el-form-item>

            <el-form-item :label-width="formLabelWidth" class="form-item">
              <template #label>
                <span style="color: red;">*</span>
                起始户数:
              </template>
              <el-input-number v-model="estateForm.elementList[index].startEstate" controls-position="right" :min="0" placeholder="请输入" autocomplete="off" style="width: 130px"></el-input-number>
              <el-button type="primary" style="margin-left: 3px;">户</el-button>
            </el-form-item>

            <el-form-item :label-width="formLabelWidth" class="form-item">
              <template #label>
                <span style="color: red;">*</span>
                每层户数:
              </template>
              <el-input-number v-model="estateForm.elementList[index].estateNum" controls-position="right" :min="0" placeholder="请输入" autocomplete="off" style="width: 130px"></el-input-number>
              <el-button type="primary" style="margin-left: 3px;">户</el-button>
              <el-button type="primary" icon="el-icon-close" @click="remove(index)" v-if="index!==0"></el-button>
              <el-button type="primary" icon="el-icon-circle-plus-outline" @click="copy" v-if="index===0"></el-button>
            </el-form-item>
          </div>
        </template>
      </el-form>
      <center>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" icon="el-icon-check" @click="dialogVisiblet">确 定</el-button>
          <el-button icon="el-icon-close" @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </center>
    </el-dialog>

    <!-- 添加或修改实有房屋对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="建造日期" prop="constructionDate">
          <el-date-picker clearable
                          v-model="form.constructionDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择建造日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="房屋图片" prop="picture">
          <!--          <el-input v-model="form.picture" placeholder="请输入房屋图片" />-->
          <ImageUpload v-model="form.picture" />
        </el-form-item>
        <el-form-item label="楼栋" prop="ridgepole">
          <el-input v-model="form.ridgepole" placeholder="请输入楼栋" />
        </el-form-item>
        <el-form-item label="单元" prop="element">
          <el-input v-model="form.element" placeholder="请输入单元" />
        </el-form-item>
        <el-form-item label="楼层" prop="tier">
          <el-input v-model="form.tier" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="房间号" prop="households">
          <el-input v-model="form.households" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="添加时间" prop="createDate">
          <el-date-picker clearable
                          v-model="form.createDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择添加时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  <!--地图对话框-->
    <el-dialog title="添加位置信息" :visible.sync="dialogFormVisiblemap">
      <center>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" icon="el-icon-check" @click="addMap">确 定</el-button>
          <el-button icon="el-icon-close" @click="dialogFormVisiblemap = false">取 消</el-button>
        </div>
      </center>
    </el-dialog>
  </div>
</template>

<script>
import { listEstate, getEstate, delEstate, addEstate, updateEstate } from "@/api/community/estate";
import { getDistrictSelect, listDistrict } from '@/api/community/district'
import { getlistPopulation, getPopulation } from '@/api/community/population'
import ImageUpload from '@/components/ImageUpload'
import { addBathEstate } from '@/api/community/estate'
export default {
  name: "Estate",
  components: { ImageUpload },
  data() {
    return {
      estateForm: {
        districtId: '',
        buildingId: '',
        elementList: [{
          name: '',
          startHouse: '',
          districtId:'',
          estateName:null,
          elementId:null,
          startFloor:null,
          endFloor:null,
          startEstate:null,
          estateNum:null,
          communityName:null
      }]
      },
      houseNumbers: [],
      options:[],
      districtList:[],
      district:[],
      selectedItems:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      //single: true,
      // 非多个禁用
      //multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实有房屋表格数据
      estateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        propertyType: null,
        constructionDate: null,
        districtId: null,
        picture: null,
        ridgepole: null,
        element: null,
        tier: null,
        households: null,
        createDate: null,
        max:null,
        min:null,
        max1:null,
        min1:null
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      dialogFormVisiblemap:false,
      // 表单参数
      form: {
        districtId:'',
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    var id = this.$route.params.id
    if (id != null && id != undefined && id !== '') {
      localStorage.setItem('districtId', id);
    }
    this.getList();
    this.getSelect();
    this.getDistrictList();
    this.getPopulationSelect();
  },
  methods: {
    // 批量导入
    handleOpen(){
      alert("导入成功")
    },
    // 跳转一屋一档车辆档案详情页面
    redirectToestatePage(item) {
      this.$router.push({
        path: '/estate/document/' + item,
        name: 'Dict',
        params: {
          item: item
        }
      })
    },
    // 添加地图确定按钮
    addMap(){
      this.dialogFormVisiblemap=false;
    },
    // 获取地图
    showMap(){
      this.dialogFormVisiblemap=true;
    },
    remove(index){
      this.estateForm.elementList.splice(index,1)
    },
    copy(){
      let elementListElement = JSON.stringify(this.estateForm.elementList[this.estateForm.elementList.length-1])
      this.estateForm.elementList.push(JSON.parse(elementListElement));
    },
    // 确定
    dialogVisiblet(){
      var item = localStorage.getItem('districtId')
      this.estateForm.districtId = item
      addBathEstate(this.estateForm).then(res => {
        this.$message.success("添加成功")
        this.dialogFormVisible=false;
        this.getList();
      });
    },
    // 添加楼栋
    add(){
      this.dialogFormVisible=true
    },
    // 房主下拉框 查询
    getPopulationSelect() {
      getlistPopulation().then(response => {
        this.options = response.data;
      });
    },
    // 查询小区 实有人口
    handlePopulationClick(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有房屋
    handleEstateClick(id) {
      this.$router.push({
        path: '/community/estate/' + id,
        name: 'Estate',
        params: {
          id: id
        }
      })
    },

    // 查询小区 实有单位
    handleUnitClick(id) {
      this.$router.push({
        path: '/community/unit/' + id,
        name: 'Unit',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有车辆
    handleVehiclesClick(id) {
      this.$router.push({
        path: '/community/vehicles/' + id,
        name: 'Vehicles',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有设备
    handleFacilitiesClick(id) {
      this.$router.push({
        path: '/community/facilities/' + id,
        name: 'Facilities',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有力量
    handleCacheClick() {
      alert('待开发');
    },
    /** 查询实有小区统计列表 */
    getDistrictList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.id = item
      listDistrict(this.queryParams).then(response => {
        this.districtList = response.rows;
        this.loading = false;
      });
    },
    /** 查询实有房屋列表 */
    getList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.districtId = item
      listEstate(this.queryParams).then(response => {
        this.estateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        propertyType: null,
        constructionDate: null,
        districtId: null,
        picture: null,
        ridgepole: null,
        element: null,
        tier: null,
        households: null,
        createDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(id) {
      if (this.selectedItems.includes(id)) {
        // 如果选中项中包含当前 id，则从 ids 中添加该 id
        if (!this.ids.includes(id)) {
          this.ids.push(id);
        }
      } else {
        // 如果选中项中不包含当前 id，则从 ids 中移除该 id
        const index = this.ids.indexOf(id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
      }
    },
    // 小区下拉框查询
    getSelect(){
      getDistrictSelect().then(res=>{
        console.log(res)
        this.district=res.data
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实有房屋";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset(); // 重置数据（假设这是清空表单等操作的方法）
      // 检查ids数组的长度
      if (this.ids.length === 1) {
        // 如果只有一个id，执行修改操作
        const id = this.ids[0];
        // 假设存在一个类似于getPopulation的函数getEstate来获取数据
        getEstate(id).then(response => {
          this.form = response.data;
          if(this.form.labelNames){
            // 如果存在labelNames，则将其分割并转换为整数数组
            this.form.labelIds=this.form.labelNames.split(',').map(id => parseInt(id));
          }
          this.open = true;
          this.title = "修改实有房屋统计"; // 根据实际情况调整标题
          this.$message.info("开始修改操作，用户：" + this.form.name); // 假设form对象中有name属性
        });
      } else if (this.ids.length > 1) {
        // 如果有多个id，提示用户每次只能修改一个项目
        this.$message.warning("每次只能修改一个实有房屋统计，请选择单个项目进行修改。");
      } else {
        // 如果没有id，提示用户选择一个项目进行修改
        this.$message.warning("请选择一个实有房屋统计项目进行修改。");
      }
    },
    /** 提交按钮 */
    submitForm() {
      var item = localStorage.getItem('districtId')
      this.form.districtId = item
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEstate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEstate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDistrictList()
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 判断是否为空
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要删除的数据");
        return;
      }
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除实有房屋编号为"' + ids + '"的数据项？').then(function() {
        return delEstate(ids);
      }).then(() => {
        this.getDistrictList()
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('community/estate/export', {
        ...this.queryParams
      }, `estate_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.form-container {
  display: flex;
  flex-wrap: wrap;
}

.form-item {
  margin-right: -27px;
  margin-bottom: 35px;
}
/* 全局样式，会影响所有el-dialog的标题 */
.el-dialog {
  background-color: #007bff !important; /* 蓝色背景 */
  color: #ffffff; /* 文本颜色设置为白色，以便在蓝色背景上可见 */
  border-radius: 4px 4px 0 0; /* 可选：给标题添加圆角，与对话框的圆角保持一致（仅上半部分） */
}
.product-content1 {
  text-align: center; /* 图片和信息居中对齐 */
  margin-bottom: 20px; /* 底部间距 */
}

.product-content1 .fixed-image-size {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 500px; /* 高度自适应，保持比例 */
  width: 500px; /* 固定宽度，可以根据需要调整 */
}

#box {
  display: flex;
  justify-content: center; /* 居中显示 */
}

.unit-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  margin: 0;
  list-style: none;
}
.unit-item {
  width: calc(33.33% - 20px); /* 计算每个项目的宽度，减去外边距 */
  margin: 10px; /* 外边距 */
}

.product-unit {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 10px;
  border: 1px solid #ccc;
  width: 100%; /* 确保每个项目占据父容器的宽度 */
}

.product-unit .fixed-image-size3 {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 200px; /* 高度自适应，保持比例 */
  width: 200px; /* 固定宽度，可以根据需要调整 */
}

.info {
  flex: 1; /* 让信息部分占据剩余空间 */
}

.info h4,
.info p {
  margin: 0;
}

.additional-info1 {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三列布局 */
  grid-gap: 10px; /* 设置网格之间的间距 */
}

.additional-info1 p {
  margin: 0;
}
</style>
